/*
 * @lc app=leetcode.cn id=438 lang=javascript
 *
 * [438] 找到字符串中所有字母异位词
 */

// @lc code=start
/**
 * @param {string} s
 * @param {string} p
 * @return {number[]}
 */
var findAnagrams = function (s, p) {
  let pLen = p.length;
  let pMap = new Map();
  let res=[]
  for (let i of p) {
    //统计p的字符个数
    pMap.set(i, pMap.get(i) ? pMap.get(i) + 1 : 1);
  }
  let flag=0
  let count=pMap.size
  let left=0,right=0
  let win=new Map()
  while(right<s.length){
      //扩张阶段
      let c=s[right]
      right++
      if(pMap.has(c)){
          win.set(c,win.get(c)?win.get(c)+1:1)
      }
      if(pMap.get(c)&&win.get(c)==pMap.get(c))flag++
      while(right-left==pLen){
          //移动阶段
          if(flag==count){
              res.push(left)
          }
          let temp=s[left]
          left++
          if(pMap.has(temp)){
              //如何恰好已满的字符少了一个
              if(win.get(temp)==pMap.get(temp)){
                  flag--
              }
              win.set(temp,win.get(temp)-1)
          }
      }
  }
  return res;
};
// @lc code=end
findAnagrams("cbaebabacd", "abc");
